<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100">
        <el-form-item label="时间范围" prop="timeScopes">
          <!-- <el-input v-noSpace v-model="queryParams.name" placeholder="请输入名字" /> -->
          <el-date-picker
            v-model="timeScopes"
            @change="validateYearRange"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            clearable
          />
        </el-form-item>
        <el-form-item label="排序方式" prop="orderBy">
          <el-radio-group v-model="queryParams.orderBy" size="large" @change="handleSeach">
            <el-radio-button
              v-for="(item, index) in SortByList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-radio-group>
        </el-form-item>

        <el-form-item label="物料筛选" prop="productCode">
          <el-select
            v-model="queryParams.productCode"
            placeholder="请输入物料筛选"
            clearable
            class="!w-[192px]"
            @change="handleSeach"
          >
            <el-option
              v-for="item in optionList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleSeach">查询</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
          <el-button
            @click="downloadTable"
            type="success"
            class="!rounded-button whitespace-nowrap"
            v-hasPerm="'sys:quantityOrder:exp'"
          >
            <el-icon class="mr-1"><Download /></el-icon>
            导出报表
          </el-button>
          <el-button
            @click="HistoryClick"
            type="info"
            class="!rounded-button whitespace-nowrap"
            v-hasPerm="'sys:quantityOrder:down'"
          >
            <el-icon class="mr-1"><Document /></el-icon>
            历史报表下载
          </el-button>
          <!-- <el-radio-group @change="handleTabClick" class="ml-3" v-model="activeTab" size="large">
            <el-radio-button
              v-for="(item, index) in activeList"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-radio-group> -->
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never" class="p0">
      <el-table
        v-loading="loading"
        show-overflow-tooltip
        :tooltip-formatter="tableRowFormatter"
        :data="tableData"
      >
        <el-table-column prop="planDate" label="计划日期" align="left"></el-table-column>
        <el-table-column prop="productName" label="物料名称" align="left" />
        <el-table-column prop="planQty" label="计划需求量" align="right"></el-table-column>
        <el-table-column prop="dosageQty" label="实际消耗量" align="right"></el-table-column>
        <el-table-column prop="unit" label="单位" align="left" />
      </el-table>
      <pagination
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleSeach"
      />
    </el-card>
    <!-- 历史报表下载弹窗 -->
    <el-dialog v-model="historyDialogVisible" title="历史报表下载" width="600px">
      <el-table :data="historyReports" style="width: 100%">
        <el-table-column prop="fileName" label="文件名称" min-width="200" />
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="100">
          <template #default="{ row }">
            <el-button @click="historyDownLoad(row.filePath, row.fileName)" type="primary" link>
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-model:total="peportTotal"
        v-model:page="reportParams.pageNum"
        v-model:limit="reportParams.pageSize"
        @pagination="reportHistoryList"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { tableRowFormatter } from "@/utils/index";
import { ref, onMounted, watch, computed } from "vue";
import { FormItemRule } from "element-plus/es";
import type { EChartsOption } from "echarts";
import * as echarts from "echarts";
import dayjs from "dayjs";
import statementApi, { locationPageQuery } from "@/api/statement/statement";
import configApi, { ConfigType } from "@/api/config/config";
import { downLoad, historyDownLoad } from "@/utils/downLoad";
import { useDateRanges } from "@/utils/useDateRanges";
const historyDialogVisible = ref(false);
const reportType = 10;
const reportName = "需求量报表";
const historyReports = ref([]);
const peportTotal = ref(0);
const reportParams: locationPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  reportType: reportType,
});
const reportHistoryList = () => {
  statementApi
    .getReportHistory(reportParams)
    .then((data) => {
      console.log(data);
      historyReports.value = [...(data.list as never)];
      historyReports.value.forEach((item: any) => {
        item.fileName = reportName + "_" + useDateRanges().getDate() + ".xlsx";
      });
      peportTotal.value = data.total;
    })
    .finally(() => {});
};
const HistoryClick = async () => {
  historyDialogVisible.value = true;
  reportHistoryList();
};
//下载表格
const downloadTable = () => {
  downLoad(queryParams, reportType, reportName);
};
const chartRef = ref<HTMLElement>();
let chart: echarts.ECharts;
const timeScopes = ref([]);

const SortByList = ref([
  {
    label: "按日期排序",
    value: 1,
  },
  {
    label: "按物料排序",
    value: 2,
  },
]);
// 限制选择范围不超过365天
const validateYearRange = (val: any) => {
  if (!val || val.length !== 2) {
    return;
  }

  const [start, end] = val;
  const startDate = new Date(start);
  const endDate = new Date(end);

  // 计算两个日期之间的年份差
  const yearDiff = endDate.getFullYear() - startDate.getFullYear();
  const monthDiff = endDate.getMonth() - startDate.getMonth();
  const dayDiff = endDate.getDate() - startDate.getDate();

  // 如果年份差大于1年，或者正好1年但结束月份/日期大于开始月份/日期
  if (yearDiff > 1 || (yearDiff === 1 && (monthDiff > 0 || (monthDiff === 0 && dayDiff > 0)))) {
    ElMessage.error(`选择的时间范围不能超过一年`);

    timeScopes.value = [];
  }
};

const sortBy = ref(1);
// 设置排序方式
const setSortBy = (type: 1 | 2) => {
  sortBy.value = type;
  console.log(sortBy, "sortBy");
};

// 加载loading
const loading = ref(false);
// 分页总数
const total = ref(0);
// 搜索ref
const queryFormRef = ref(ElForm);
// 一级弹窗ref
const dialogFormRef = ref(ElForm);
//一级弹窗
const dialogVisible = reactive({ visible: false, title: "", type: "" });
//一级表单验证
const rules = reactive<Record<string, FormItemRule[]>>({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  type: [{ required: true, message: "请输入类型", trigger: "blur" }],
});

const queryParams: locationPageQuery = reactive({
  pageNum: 1,
  pageSize: 10,
  orderBy: 1,
});
// 类型
const optionList = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const getContractLists = () => {
  configApi
    .getProductList({ pageNum: 1, pageSize: 999 })
    .then((data) => {
      console.log(data, "data");
      // rowTableData.value = data?.list || [];
      optionList.value = (data?.list || []).map((item: any) => ({
        value: item.code,
        label: item.productName,
      }));
    })
    .catch((error) => {
      //ElMessage.error(`${error}`); //注释报错弹窗
    })
    .finally(() => {});
};

// 列表参数
const tableData = ref([]);
const dialogFormData: {
  id?: string;
  name?: string;
  type?: number;
} = reactive({});
// 查询方法
const handleSeach = () => {
  loading.value = true;
  queryParams.startDate = timeScopes.value[0];
  queryParams.endDate = timeScopes.value[1];
  statementApi
    .getProdBomReport(queryParams)
    .then((data) => {
      tableData.value = [...(data.list as never)];
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
};
// 重置方法
const handleReset = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  timeScopes.value = [];
  handleSeach();
};

onMounted(() => {
  handleSeach();
  getContractLists();
});
</script>

<style lang="scss" scoped>
@use "@/styles/css/public" as *;
.el-checkbox-button :deep(.el-checkbox-button__inner) {
  border-radius: 4px;
  margin-right: 8px;
  border: 1px solid #dcdfe6;
}
.el-checkbox-button.is-checked :deep(.el-checkbox-button__inner) {
  border-color: var(--el-color-primary);
}
:deep(.el-card__body) {
  padding: 0 20px !important;
}
</style>
